﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UIWindow.Helper
{
    /// <summary>
    /// 对象转字节扩展类
    /// </summary>
    public static class ObjectToBytes
    {
        /// <summary>
        /// FCS校验
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string FCS(this string data)
        {
            byte[] bytes = Encoding.ASCII.GetBytes(data);
            int xorresult = bytes[0];
            for (int i = 1; i < bytes.Length; i++)
            {
                xorresult = xorresult ^ bytes[i];
            }
            return $"{Convert.ToString(xorresult, 16):00}";
        }
        /// <summary>
        /// 对象转ASCII码
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static byte[] ObjectToASCII<T>(this T value)
        {
            return Encoding.ASCII.GetBytes(value.ToString());
        }
        /// <summary>
        /// ASCII码转字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ASCIIToString(this byte[] bytes)
        {
            return Encoding.ASCII.GetString(bytes);
        }

        /// <summary>
        /// 字节转整形
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static int ByteToInt(this byte[] bytes)
        {
            return (bytes[0] << 24) + (bytes[1] << 16) + (bytes[2] << 8) + bytes[3];
        }

        /// <summary>
        /// 地址数据转换
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static byte[] StrToHexByte(this string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }
    }
}
